package com.edu.edu.day9_19_week7_homework.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.edu.edu.day9_19_week7_homework.R;
import com.edu.edu.day9_19_week7_homework.activity.DetailActivity;
import com.edu.edu.day9_19_week7_homework.adapter.FoodAdapter;
import com.edu.edu.day9_19_week7_homework.bean.Food;
import com.edu.edu.day9_19_week7_homework.thread.LoadJsonTask;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContentFragment extends Fragment implements LoadJsonTask.onGetJsonResultListener {

    private FoodAdapter adapter;
    private PullToRefreshGridView mRefresh;
    private String JSON_URL;
    private GridView mGridView;
    private int currentPage = 1;//page值
    private int count=10;
    private String path;

    public ContentFragment() {
        // Required empty public constructor
    }
    //用来创建fragmnet对象
    public static ContentFragment createFragment(int position){
        ContentFragment fragmnet = new ContentFragment();
        return fragmnet;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_content, container, false);
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);//初始化控件
        initData();//初始化数据
        initRefresh();//刷新界面

    }


    private void initData() {
        //根据bundle取值
        Bundle args = getArguments();
        //根据key获得url网址
        JSON_URL =  args.getString("key");
        //开启异步任务
        initJsonData();
        assert mRefresh != null;
        //创建适配器
        adapter = new FoodAdapter(getActivity());
        //设置适配器
        mRefresh.setAdapter(adapter);

        //GridView的点击事件，点击跳转到详情页面
        mRefresh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //获取点击条目的数据
                Food food = (Food)adapter.getItem(position);
                String caption = food.getCaption();
                String video = food.getVideo();
                String type = food.getType();
                //根据type值判断是否有视频资源
                if(type.equals("media")){
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    //通过key传字符串
                    intent.putExtra("caption",caption);
                    intent.putExtra("video",video);
                    startActivity(intent);
                }else{
                    Toast.makeText(getActivity(),"当前条目没有详情页！",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //下拉刷新
    private void initRefresh() {
        //上下拉刷新监听
        mRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            //下拉刷新方法
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                //设置刷新时显示当前时间
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                currentPage++;//每次刷新更新下一页数据
                initJsonData();//开启异步任务
                adapter.notifyDataSetChanged();//刷新数据
                mRefresh.onRefreshComplete();//停止刷新操作
            }
            //上拉刷新方法
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
//                currentPage++;//每次刷新更新下一页数据
//                initJsonData();//开启异步任务
                initUpData();//向上刷新
                adapter.notifyDataSetChanged();//刷新数据
                mRefresh.onRefreshComplete();//停止刷新操作
            }
        });
    }
    //初始化数据
    private void initUpData(){
        count++;
        //当默认加载第一页的时候，每次向上刷新，往后增加1个数据
        if(currentPage == 1){
            String path = JSON_URL.replace("10",count+"");
            new LoadJsonTask(this).execute(path);
        }else{
            //如果不是第一页，如果先往下刷新，page值改变，然后往上刷新
            //则page值为当前页面page值，往后增加一个数据
            String url = path.replace("10",count+"");
            new LoadJsonTask(this).execute(url);
        }

    }
    //初始化数据
    private void initJsonData(){
        path = String.format(JSON_URL,currentPage);
        new LoadJsonTask(this).execute(path);

    }
    //初始化控件
    private void initView(View view) {
        mRefresh = (PullToRefreshGridView)view.findViewById(R.id.refresh);
        mRefresh.setMode(PullToRefreshBase.Mode.BOTH);//设置刷新模式【上下拉刷新】
        //在刷新时允许继续滑动
        mRefresh.setScrollingWhileRefreshingEnabled(true);
        mGridView = mRefresh.getRefreshableView();


    }
    //回调接口
    @Override
    public void onGetJsonResult(List<Food> result) {
        adapter.setData(result);
    }
}
